﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.Common;
using System.Web.Security;
using System.Web.Profile;
using smartphone.SecurityLib;
using System.Text;

namespace smartphone.App_Code
{
    /// <summary>
    /// Wraps tax data
    /// </summary>
    public struct TaxInfo
    {
      public int TaxID;
      public string TaxType;
      public double TaxPercentage;
    }

    public class CommerceLibAccess
    {
        /// <summary>
        /// lay thong tin chi tiet cua 1 don hang bao gom cac thong tin ve san pham trong don hang do
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public static List<CommerceLibOrderDetailInfo> GetOrderDetails(string orderId)
        {
            Order order = new Order();
            DataTable table = order.GetDetails(orderId);
            List<CommerceLibOrderDetailInfo> orderDetailList = new
                List<CommerceLibOrderDetailInfo>(table.Rows.Count);

            foreach (DataRow row in table.Rows)
            {
                orderDetailList.Add(new CommerceLibOrderDetailInfo(row));
            }

            return orderDetailList;
        }

        /// <summary>
        /// thong tin don hang
        /// </summary>
        /// <param name="orderID"></param>
        /// <returns></returns>
        public static CommerceLibOrderInfo GetOrder(string orderID)
        {
            DbCommand comm = GenericDataAccess.CreateCommand();
            comm.CommandText = "CommerceLibOrderGetInfo";

            DbParameter param = comm.CreateParameter();
            param.ParameterName = "@OrderID";
            param.Value = orderID;
            param.DbType = DbType.Int32;
            comm.Parameters.Add(param);
            
            DataTable table = GenericDataAccess.ExecuteSelectCommand(comm);
            DataRow orderRow = table.Rows[0];
            
            //goi ham khoi tao truyen vao DataRow chua thong tin ve do hang
            CommerceLibOrderInfo orderInfo = new CommerceLibOrderInfo(orderRow);
            return orderInfo;
        }
    }

    //chi tiet don hang
    public class CommerceLibOrderDetailInfo
    {
        //ma don hang
        public int OrderID;
        //ma san pham
        public int ProductID;
        //ten san pham
        public string ProductName;
        //so luong
        public int Quantity;
        //gia tung san pham
        public double UnitCost;
        //mo ta
        public string ItemAsString;

        //lay tong tien tung san pham
        public double Subtotal
        {
            get
            {
                return Quantity * UnitCost;
            }
        }

        //ham khoi tao voi gia tri lay tu 1 DataRow
        public CommerceLibOrderDetailInfo(DataRow orderDetailRow)
        {
            OrderID = Int32.Parse(orderDetailRow["maDonHang"].ToString());
            ProductID = Int32.Parse(orderDetailRow["maSanPham"].ToString());
            ProductName = orderDetailRow["tenSanPham"].ToString();
            UnitCost = Double.Parse(orderDetailRow["donGia"].ToString());

            Refresh();
        }

        //
        private void Refresh()
        {
            ItemAsString = "Có " + Quantity.ToString() + " " + ProductName.ToString()
                + " mỗi sản phẩm trị giá " + UnitCost.ToString()
                + " giá " + Subtotal.ToString();
        }

    }

    /// <summary>
    /// Class don hang
    /// </summary>
    public class CommerceLibOrderInfo
    {
        //ma don hang
        public int OrderID;
        //ngay tao don hang
        public string DateCreated;
        //ngay don hang giao
        public string DateShipped;
        //thong tin bo sung cho don hang
        public string Comments;
        //tinh trang cua don hang
        public int Status;
        //ma bao mat
        public string AuthCode;
        //The unique reference code of the customer credit card transaction
        public string Reference;
        //thong tin ve khach hang
        public MembershipUser Customer;
        public UserProfile CustomerProfile;
        //tai khoan
        public SecureCard CreditCard;
        //tong chi phi
        public double TotalCost;
        public string OrderAsString;
        public string CustomerAddressAsString;

        public TaxInfo Tax;

        public List<CommerceLibOrderDetailInfo> OrderDetails;

        public CommerceLibOrderInfo(DataRow orderRow)
        {
            OrderID = Int32.Parse(orderRow["maDonHang"].ToString());
            DateCreated = orderRow["ngayTao"].ToString();
            DateShipped = orderRow["ngayGiaoHang"].ToString();
            Comments = orderRow["thongTin"].ToString();
            Status = Int32.Parse(orderRow["tranhThai"].ToString());
            AuthCode = orderRow["AuthCode"].ToString();
            Reference = orderRow["Reference"].ToString();

            Customer = Membership.GetUser(new Guid(orderRow["CustomerID"].ToString()));
            CustomerProfile = UserProfile.GetUserProfile(Customer.UserName);

            CreditCard = new SecureCard(CustomerProfile.CreditCard);
            OrderDetails = CommerceLibAccess.GetOrderDetails(orderRow["OrderID"].ToString());

            //lay thong tin ve thue
            if (orderRow["maThue"] != DBNull.Value && orderRow["loaiThue"] != DBNull.Value &&
                    orderRow["phanTramThue"] != DBNull.Value)
            {
                Tax.TaxID = Int32.Parse(orderRow["maThue"].ToString());
                Tax.TaxType = orderRow["loaiThue"].ToString();
                Tax.TaxPercentage = double.Parse(orderRow["phanTramThue"].ToString());
            }
            else
            {
                Tax.TaxID = -1;
            }
            // set info properties
            Refresh();
        }

        public void Refresh()
        {
            // calculate total cost and set data
            StringBuilder sb = new StringBuilder();
            TotalCost = 0.0;
            foreach (CommerceLibOrderDetailInfo item in OrderDetails)
            {
                sb.AppendLine(item.ItemAsString);
                TotalCost += item.Subtotal;
            }

            // them thue
            if (Tax.TaxID != -1 && Tax.TaxPercentage != 0.0)
            {
                double taxAmount = Math.Round(TotalCost * Tax.TaxPercentage,
                MidpointRounding.AwayFromZero) / 100.0;
                sb.AppendLine("Tax: " + Tax.TaxType + ", $"
                + taxAmount.ToString());
                TotalCost += taxAmount;
            }

            sb.AppendLine();
            sb.Append("Tổng tiền phải trả: $");
            sb.Append(TotalCost.ToString());
            OrderAsString = sb.ToString();
            // lấy địa chỉ khách
            sb = new StringBuilder();
            sb.AppendLine(Customer.UserName);
            sb.AppendLine(CustomerProfile.Address1);
            if (CustomerProfile.Address2 != "")
            {
                sb.AppendLine(CustomerProfile.Address2);
            }
            sb.AppendLine(CustomerProfile.City);
            sb.AppendLine(CustomerProfile.Region);
            sb.AppendLine(CustomerProfile.PostalCode);
            sb.AppendLine(CustomerProfile.Country);
            CustomerAddressAsString = sb.ToString();
        }
    }
}
    